<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb class="el-breadcrumb" separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图 -->
		<el-card class="el-card">
			<!-- 添加角色按钮区域 -->
			<div class="add-roles-btn">
				<el-row  :span="24">
					<el-col>
						<el-button @click="addRoleBtnClick" type="primary">添加角色</el-button>
					</el-col>
				</el-row>
			</div>
			<!-- 表格区域 -->
			<el-row :span="24">
				<el-col>
					<el-table class="el-table" border stripe :data="rolesList">
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-row :class="[i1===0?'role-el-row-first':'role-el-row', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
									<!-- 渲染一级权限 -->
									<el-col :span="5">
										<el-tag @close="tagClose(scope.row, item1.id)" closable class="role-el-tag">{{item1.authName}}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<!-- 渲染二级权限和三级权限 -->
									<el-col :span="19">
										<el-row :class="[i2===0?'':'role-el-row-first-2', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
												<el-col :span="6">
													<el-tag @close="tagClose(scope.row, item2.id)" closable class="role-el-tag">{{item2.authName}}</el-tag>
													<i class="el-icon-caret-right"></i>
												</el-col>
												<el-col :span="13">
													<el-tag @close="tagClose(scope.row, item3.id)" closable :key="item3.id" v-for="item3 in item2.children" class="role-el-tag">{{item3.authName}}</el-tag>
												</el-col>
										</el-row>
									</el-col>
								</el-row>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="角色名称" prop="roleName"></el-table-column>
						<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
						<!-- 表格内操作区 -->
						<el-table-column label="操作">
							<template slot-scope="scope">
								<!-- 编辑按钮 -->
								<el-button @click="reviseRoleBtnClick(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
								<!-- 删除按钮 -->
								<el-button @click="deleteRoleBtnClick(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
								<!-- 分配权限按钮 -->
								<el-button @click="showSetRightDialog(scope.row)" size="mini" type="success" icon="el-icon-setting">分配权限</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>
		</el-card>
		<!-- 对话框dialog区域 -->
			<!-- 添加角色对话框 -->
		<el-dialog @close="addRolesDialogClose" title="添加角色" :visible.sync="addRolesDialogVisible" width="50%">
			<el-form label-width="80px" ref="addRolesRef" :model="addRoleForm" :rules="addRoleFormRule">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="addRoleForm.roleName"></el-input>
				</el-form-item>
				<el-form-item label="角色描述" prop="roleDesc">
					<el-input v-model="addRoleForm.roleDesc"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addRolesDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="allotRoles">确 定</el-button>
			</div>
		</el-dialog>
			<!-- 分配权限对话框 -->
		<el-dialog @close="setRightsDialogClose" title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
			<!-- 树形组件 -->
			<el-tree ref="treeRef" :default-checked-keys="treeExpandedKeys" node-key="id" default-expand-all show-checkbox :data="rightsList" :props="treeProps"></el-tree>
			<div slot="footer" class="dialog-footer">
				<el-button @click="setRightDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="allotRights">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data () {
			return {
					// 添加角色对话框绑定表单验证规则
				addRoleFormRule: {
					roleName: [
						{ required: true, message: '请输入角色名', trigger: 'blur' }
					],
					roleDesc: [
						{ required: true, message: '请输入角色描述', trigger: 'blur' }
					]
				},
					// 添加角色对话框绑定表单数据
				addRoleForm: {
					roleName: '',
					roleDesc: ''
				},
					// 添加角色对话框开关
				addRolesDialogVisible: false,
				currentId: 0,
				// currentKeys: [],
				treeExpandedKeys: [],
				treeProps: {
					children: 'children',
					label: 'authName'
				},
				setRightDialogVisible: false,
				rolesList: [],
				rightsList: []
			}
		},
		methods: {
				// 事件：添加角色对话框确认按钮点击时
			async allotRoles () {
				// this.$refs.addRolesRef.
				const { data: res } = await this.$http.post('roles', this.addRoleForm)
				if (res.meta.status !== 201) {
					return this.$message.error('添加角色失败')
				}
				this.getRolesList()
				this.addRolesDialogVisible = false
			},
				// 事件：添加角色对话框关闭时
			addRolesDialogClose () {
				this.$message.success('addRolesDialogClose')
				// this.$refs.addRolesRef.resetFields()
				this.$refs.addRolesRef.resetFields()
				// this.addRoleForm.roleName = ''
				// this.addRoleForm.roleDesc = ''
			},
				// 事件：添加角色按钮点击时
			addRoleBtnClick () {
					// this.$message.success('addRoleBtnClick')
				this.addRolesDialogVisible = true
			},
				// 事件：当删除按钮点击时
			async deleteRoleBtnClick (roleId) {
					// this.$message.success('deleteRoleBtnClick')
					// console.log(roleId)
				const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).catch(err => err)
				if (confirmResult !== 'confirm') {
					return this.$message.success('已取消删除')
				}
				const { data: res } = await this.$http.delete(`roles/${roleId}`)
					// console.log(res)
				if (res.meta.status !== 200) {
					return this.$message.error('删除角色失败')
				}
				this.$message.error('删除角色成功')
					// 更新页面
				this.getRolesList()
			},
			async allotRights () {
				const keys = [
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys()
				]
					// console.log(keys)
				const idStr = keys.join(',')
				const { data: res } = await this.$http.post(`roles/${this.currentId}/rights`, { rids: idStr })
					// console.log(res)
				if (res.meta.status !== 200) {
					return this.$message.error('修改角色权限失败')
				}
				this.setRightDialogVisible = false
				this.$message.success('修改角色权限成功')
				this.getRolesList()
			},
			// 事件：点击树形控件复选框，打印测试文本
				// checkClick () {
				// 	console.log(this.treeExpandedKeys)
				// },
			// 事件：在分配权限对话框关闭时，清空默认勾选treeExpandedKeys数据
			setRightsDialogClose () {
				this.treeExpandedKeys = []
			},
			// 函数：通过递归方式，获取第三权限id，赋值给treeExpandedKeys
			getLeafKeys (node, arr) {
				if (!node.children) {
					return arr.push(node.id)
				}
				node.children.forEach(item => {
					this.getLeafKeys(item, arr)
				})
			},
			// 事件：点击分配权限按钮，触发展示添加权限对话框
			async showSetRightDialog (scopeRow) {
				// this.$message.success('showSetRightDialog')
				// 获取所有权限数据
				console.log(scopeRow)
				const { data: res } = await this.$http.get('rights/tree')
				if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
				this.rightsList = res.data
				this.currentId = scopeRow.id
				// console.log(this.currentId)
				// console.log(this.rightsList)
				// 递归获取三级权限id
				this.getLeafKeys(scopeRow, this.treeExpandedKeys)
				// console.log(this.treeExpandedKeys)
				this.setRightDialogVisible = true
			},
			// 事件：删除权限触发事件
			async tagClose (role, rightId) {
				// this.$message.success('tagClose')
				console.log(role, rightId)
				const confirmResult = await this.$confirm('是否要删除该权限？', '提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				console.log(confirmResult)
				if (confirmResult !== 'confirm') {
					return this.$message.success('已取消删除')
				}
				// 下面写发送请求删除权限的代码
				const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
				// console.log(res)
				if (res.meta.status !== 200) {
					return this.$message.success('删除角色权限失败')
				}
				// this.getRolesList()
				role.children = res.data
			},
			// 函数：获取角色列表
			async getRolesList () {
				// this.$message.success('getRolesList')
				const { data: res } = await this.$http.get('roles')
				if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
				this.rolesList = res.data
				// console.log(this.rolesList)
			}
		},
		created () {
			this.getRolesList()
		}
	}
</script>

<style lang="less" scoped>
	.el-breadcrumb {
		margin-bottom: 15px;
	}
	.el-card {
		box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
	}
	.add-roles-btn {
		margin-bottom: 15px;
	}
	.role-el-tag {
		margin: 10px;
	}
	.role-el-row {
		border-bottom: 1px solid #ffccff;
	}
	.role-el-row-first {
		border-bottom: 1px solid #ffccff;
		border-top: 1px solid #ffccff;
	}
	.role-el-row-first-2 {
		border-top: 1px solid #ffccff;
	}
	.vcenter {
		display: flex;
		align-items: center;
	}
</style>
